package com.example.yunifang;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.pay.demo.H5PayDemoActivity;
import com.alipay.sdk.pay.demo.PayResult;
import com.alipay.sdk.pay.demo.SignUtils;
import com.example.yunifang.adapter.MyXiangQingAdapter;
import com.example.yunifang.bean.GouWuCheBean;
import com.example.yunifang.bean.XiangQingBean;
import com.example.yunifang.bean.XiangQingBean.Data.Activity1;
import com.example.yunifang.bean.XiangQingBean.Data.Comments;
import com.example.yunifang.bean.XiangQingBean.Data.Goods.Attributes;
import com.example.yunifang.bean.XiangQingChildrenBean;
import com.example.yunifang.dao.GouWuCheDao;
import com.example.yunifang.fragment.CanShuFragment;
import com.example.yunifang.fragment.Fragment3;
import com.example.yunifang.fragment.PinLunFragment;
import com.example.yunifang.fragment.XiangQingFragment;
import com.example.yunifang.myview.MyListView;
import com.example.yunifang.myview.MyScrollView;
import com.example.yunifang.myview.MyScrollView.OnScrollListener;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;

public class XiangQingActivity extends FragmentActivity implements
		OnClickListener, OnScrollListener {

	private ImageView xiangqing_img;
	private int id;
	private TextView xiangqing_name;
	private TextView xiangqing_price;
	private TextView xiangqing_market_price;
	private TextView xiangqing_xiaoliang;
	private TextView xiangqing_shoucang;
	private MyListView xiangqing_lv;
	ArrayList<Activity1> data = new ArrayList<Activity1>();
	public static ArrayList<Attributes> list = new ArrayList<Attributes>();
	public static ArrayList<Comments> comments = new ArrayList<XiangQingBean.Data.Comments>();
	private RadioButton xiangqing_rb1;
	private RadioButton xiangqing_rb2;
	private RadioButton xiangqing_rb3;
	private FragmentManager manager = getSupportFragmentManager();
	private FrameLayout xiangqing_vp;
	private XiangQingBean bean;
	private MyListView xiangqing_lv_canshu;
	private RelativeLayout rlayout;
	private MyScrollView myScrollView;
	public static XiangQingChildrenBean[] bean2;
	private int searchLayoutTop;
	private RadioGroup radioG;
	private LinearLayout search01;
	private LinearLayout search02;
	private RadioButton back_radio;
	private RadioButton xiangqing_fenxiang;
	private TextView xiangqing_lijigoumai;
	private TextView xiangqing_jiarugouwuche;
	private View view;
	private PopupWindow pop;
	private TextView pop_queding;
	private TextView pop_price;
	private TextView pop_num;
	private TextView pop_kucun;
	private ImageView pop_img;
	private Button pop_jian;
	private Button pop_jia;
	// 商户PID
			public static final String PARTNER = "2088901305856832";
			// 商户收款账号
			public static final String SELLER = "8@qdbaiu.com";
			// 商户私钥，pkcs8格式
			public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAM/KCxg/OIj6er2GEig0DOkHqBSzEPHGigMbTXP1k2nrxEHeE59xOOuyovQH/A1LgbuVKyOac3uAN4GXIBEoozRVzDhu5dobeNm48BPcpYSAfvN3K/5GLacvJeENqsiBx8KufM/9inlHaDRQV7WhX1Oe2ckat1EkdHwxxQgc36NhAgMBAAECgYEAwn3sWpq6cUR65LD8h9MIjopTImTlpFjgz72bhsHDZK6A+eJDXcddrwh7DI34t/0IBqu+QEoOc/f0fIEXS9hMwTvFY59XG7M8M6SdeaAbemrGmZ1IdD6YDmpbQFHn2ishaYF0YDZIkBS3WLDFrtk/efaarBCpGAVXeEiVQE4LewECQQD5W1rpkq+dHDRzzdtdi1bJ479wun5CfmVDVb2CJH7Iz0t8zyp/iEVV2QELnxZMphmoSzKaLXutTTj2OImpzCtRAkEA1VMxG6nQq9NkU51H1+I3mlUXRZ0XeFA1GFJ7xWpNRAVhEWlDz2zy9v/gX+RFpNC3f5uznycas70Xp78ew43TEQJAZFFqi9mlqTF1sLk67bFnIyXrGPEOZrXvC13tNfR0xVkQZ4/46wHp0xXQo9pG4GNaoyhNnVV7EkelCPnJ+HPZYQJAQh6T9QgQZoGR8hyovPAf3dUL7oa/VIo/urcuJ8VIB5JHQNdIrk0NjaNHj1E4iNosVgATj3vWWel9IIArb99QkQJAKvfm78lwnImtg5IM604hdn/Wu1XF8tpxsKLWcnfchMr0bM9rCmKmhAY+wdmqSyPZRiNb1QaaaDTqJxLy6AnQ+Q==";
			// 支付宝公钥
			public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCd6rV3vOE578e6VlGEakZpPdsX2QmGdIfi/yHe cg1CIEWzX9wn2LNFGtu1EzYQyKACG/RKeog0pUJEVGfBG30zFdNY2YocYJNdPtADqhJbS0GJm7f8 1vRiLKtOwKjdiz9oMEwxhc/5fysfMbercidRmlCDPU9BNL1UPb9bAx25JwIDAQAB";
			private static final int SDK_PAY_FLAG = 1;

			@SuppressLint("HandlerLeak")
			private Handler mHandler = new Handler() {
				@SuppressWarnings("unused")
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case SDK_PAY_FLAG: {
						PayResult payResult = new PayResult((String) msg.obj);
						/**
						 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
						 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
						 * docType=1) 建议商户依赖异步通知
						 */
						String resultInfo = payResult.getResult();// 同步返回需要验证的信息

						String resultStatus = payResult.getResultStatus();
						// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
						if (TextUtils.equals(resultStatus, "9000")) {
							Toast.makeText(XiangQingActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
						} else {
							// 判断resultStatus 为非"9000"则代表可能支付失败
							// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
							if (TextUtils.equals(resultStatus, "8000")) {
								Toast.makeText(XiangQingActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

							} else {
								// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
								Toast.makeText(XiangQingActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

							}
						}
						break;
					}
					default:
						break;
					}
				};
			};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_xiang_qing);
		id = getIntent().getIntExtra("id", 0);
		init();
		getJson();
	}

	public void init() {
		xiangqing_img = (ImageView) findViewById(R.id.xiangqing_img);
		xiangqing_name = (TextView) findViewById(R.id.xiangqing_name);
		xiangqing_price = (TextView) findViewById(R.id.xiangqing_price);
		xiangqing_market_price = (TextView) findViewById(R.id.xiangqing_market_price);
		xiangqing_xiaoliang = (TextView) findViewById(R.id.xiangqing_xiaoliang);
		xiangqing_shoucang = (TextView) findViewById(R.id.xiangqing_shoucang);
		xiangqing_lv = (MyListView) findViewById(R.id.xiangqing_lv);
		xiangqing_rb1 = (RadioButton) findViewById(R.id.xiangqing_rb1);
		xiangqing_rb2 = (RadioButton) findViewById(R.id.xiangqing_rb2);
		xiangqing_rb3 = (RadioButton) findViewById(R.id.xiangqing_rb3);
		xiangqing_vp = (FrameLayout) findViewById(R.id.xiangqing_vp);
		rlayout = (RelativeLayout) findViewById(R.id.rlayout);
		myScrollView = (MyScrollView) findViewById(R.id.myscrollview);
		radioG = (RadioGroup) findViewById(R.id.radioG);
		search01 = (LinearLayout) findViewById(R.id.search01);
		search02 = (LinearLayout) findViewById(R.id.search02);
		back_radio = (RadioButton) findViewById(R.id.back_radio);
		xiangqing_lijigoumai = (TextView) findViewById(R.id.xiangqing_lijigoumai);
		xiangqing_jiarugouwuche = (TextView) findViewById(R.id.xiangqing_jiarugouwuche);
		xiangqing_lijigoumai.setOnClickListener(this);
		xiangqing_jiarugouwuche.setOnClickListener(this);
		xiangqing_fenxiang = (RadioButton) findViewById(R.id.xiangqing_fenxiang);
		xiangqing_fenxiang.setOnClickListener(this);
		back_radio.setOnClickListener(this);
		myScrollView.setOnScrollListener(this);
		xiangqing_rb1.setTextColor(Color.RED);
		xiangqing_rb3.setOnClickListener(this);
		xiangqing_rb2.setOnClickListener(this);
		xiangqing_rb1.setOnClickListener(this);
	}

	private void getJson() {
		// TODO Auto-generated method stub
		HttpUtils utils = new HttpUtils();
		utils.send(
				HttpMethod.GET,
				"http://m.yunifang.com/yunifang/mobile/goods/detail?random=6716&encode=b02382bd9e457e06e09b68a6a4f26eb4&id="
						+ id, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						String json = arg0.result;
						Gson gson = new Gson();
						bean = gson.fromJson(json, XiangQingBean.class);
						getData(bean);
						getInit(bean);
						getSupportFragmentManager()
								.beginTransaction()
								.replace(R.id.xiangqing_vp,
										new XiangQingFragment()).commitAllowingStateLoss();

						popInit(bean);
						if (bean.data.comments != null) {
							comments.clear();
							comments.addAll(bean.data.comments);
						}
					}

				});
	}

	int i = 1;
	private TextView pop_buy_num;
	private int num;

	public void popInit(XiangQingBean bean) {
		view = getLayoutInflater().inflate(R.layout.pop_dialog, null);
		pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		pop_queding = (TextView) view.findViewById(R.id.pop_queding);
		pop_price = (TextView) view.findViewById(R.id.pop_price);
		pop_num = (TextView) view.findViewById(R.id.pop_num);
		pop_kucun = (TextView) view.findViewById(R.id.pop_kuncun);
		pop_img = (ImageView) view.findViewById(R.id.pop_img);
		pop_jian = (Button) view.findViewById(R.id.pop_jian);
		pop_jia = (Button) view.findViewById(R.id.pop_jia);
		pop_buy_num = (TextView) view.findViewById(R.id.pop_buy_num);
		float price = bean.data.goods.shop_price;
		int kuncun = bean.data.goods.stock_number;
		num = bean.data.goods.restrict_purchase_num;
		pop_price.setText("￥" + price);
		pop_kucun.setText("库存" + kuncun + "件");
		pop_num.setText("限购" + num + "件");
		pop.setBackgroundDrawable(new ColorDrawable(0));
		ImageLoader.getInstance().displayImage(bean.data.goods.goods_img,
				pop_img);
		pop.setOutsideTouchable(true);
		pop.setFocusable(true);// 点击back退出pop
		pop.setAnimationStyle(R.style.add_new_style);
		pop.setTouchable(true);

		final GouWuCheDao dao = new GouWuCheDao(this);
		final GouWuCheBean bean2 = new GouWuCheBean();

		pop.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				// TODO Auto-generated method stub
				backgroundAlpha(XiangQingActivity.this, 1f);
			}
		});

		pop.setTouchInterceptor(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
					pop.dismiss();
					backgroundAlpha(XiangQingActivity.this, 1f);
					return true;
				}
				return false;
			}
		});

		pop_jia.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				i++;
				if (i <= 1) {
					Toast.makeText(XiangQingActivity.this, "至少选择一件商品", 0)
							.show();
					i = 1;
				} else if (i >= num) {
					Toast.makeText(XiangQingActivity.this,
							"最多购买" + num + "件商品", 0).show();
					i = num;
				}
				bean2.setNum(i);
				pop_buy_num.setText(i + "");
			}
		});
		pop_jian.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				i--;
				if (i < 1) {
					Toast.makeText(XiangQingActivity.this, "至少选择一件商品", 0)
							.show();
					i = 1;
				} else if (i > num) {
					Toast.makeText(XiangQingActivity.this,
							"最多购买" + num + "件商品", 0).show();
					i = num;
				}
				bean2.setNum(i);
				pop_buy_num.setText(i + "");
			}
		});
		bean2.setImg(bean.data.goods.goods_img);
		bean2.setName(bean.data.goods.goods_name);
		bean2.setNum(i);
		bean2.setPrice(bean.data.goods.shop_price);
		bean2.setShop_id(id + "");
		pop_queding.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pop.dismiss();
				if (id != 0) {
					dao.add(bean2);
					Toast.makeText(XiangQingActivity.this, "加入购物车成功", 0).show();
				}
				backgroundAlpha(XiangQingActivity.this, 1f);

			}
		});

		pop_buy_num.setText(i + "");
	}

	public void backgroundAlpha(Activity context, float bgAlpha) {
		WindowManager.LayoutParams lp = context.getWindow().getAttributes();
		lp.alpha = bgAlpha;
		context.getWindow()
				.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		context.getWindow().setAttributes(lp);
	}

	public void getData(final XiangQingBean bean) {
		ImageLoader.getInstance().displayImage(bean.data.goods.goods_img,
				xiangqing_img);
		xiangqing_name.setText(bean.data.goods.goods_name);
		xiangqing_price.setText("￥" + bean.data.goods.shop_price + "");
		xiangqing_market_price.setText(bean.data.goods.market_price + "");
		xiangqing_market_price.getPaint().setFlags(
				Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
		xiangqing_xiaoliang.setText(bean.data.goods.collect_count + "");
		xiangqing_shoucang.setText(bean.data.goods.stock_number + "");
		MyXiangQingAdapter adapter = new MyXiangQingAdapter(data, this);
		xiangqing_lv.setAdapter(adapter);
		xiangqing_lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String str = bean.data.activity.get(arg2).description;
				Intent intent = new Intent(XiangQingActivity.this,
						ZhuWebActivity.class);
				intent.putExtra("str", str);
				startActivity(intent);
			}
		});
		xiangqing_rb3.setText("评论(" + bean.data.commentNumber + ")");
		String json = bean.data.goods.goods_desc;
		Gson gson = new Gson();
		bean2 = gson.fromJson(json, XiangQingChildrenBean[].class);
		FragmentManager manager = getSupportFragmentManager();
	}

	public void getInit(XiangQingBean bean) {
		data.clear();
		data.addAll(bean.data.activity);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.xiang_qing, menu);
		return true;
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.xiangqing_rb1:
			// fragment = new XiangQingFragment();
			xiangqing_rb1.setTextColor(Color.RED);
			xiangqing_rb2.setTextColor(Color.BLACK);
			xiangqing_rb3.setTextColor(Color.BLACK);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.xiangqing_vp, new XiangQingFragment())
					.commitAllowingStateLoss();
			// xiangqing_vp.setCurrentItem(0);
			break;
		case R.id.xiangqing_rb2:
			list.clear();
			list.addAll(bean.data.goods.attributes);
			xiangqing_rb1.setTextColor(Color.BLACK);
			xiangqing_rb2.setTextColor(Color.RED);
			xiangqing_rb3.setTextColor(Color.BLACK);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.xiangqing_vp, new CanShuFragment()).commitAllowingStateLoss();
			// xiangqing_vp.setCurrentItem(1);
			break;
		case R.id.xiangqing_rb3:
			if (bean.data.comments != null) {
				comments.clear();
				comments.addAll(bean.data.comments);
			}
			xiangqing_rb1.setTextColor(Color.BLACK);
			xiangqing_rb2.setTextColor(Color.BLACK);
			xiangqing_rb3.setTextColor(Color.RED);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.xiangqing_vp, new PinLunFragment()).commitAllowingStateLoss();
			// xiangqing_vp.setCurrentItem(2);
			break;
		case R.id.back_radio:
			finish();
			overridePendingTransition(R.anim.infragment, R.anim.outfragment);
			break;
		case R.id.xiangqing_fenxiang:
			showShare();
			break;
		case R.id.xiangqing_jiarugouwuche:
			ColorDrawable dw = new ColorDrawable(0x00000000);
			if (pop != null) {
				pop.setBackgroundDrawable(dw);
				backgroundAlpha(XiangQingActivity.this, 0.5f);
				if (bean != null) {
					if (pop.isShowing()) {
						pop.dismiss();
					} else {
						pop.showAtLocation(view, Gravity.BOTTOM, 0, -560);// 在父控件下方出来
						// pop.showAsDropDown(view);
					}
					pop.showAsDropDown(view);
				}
			}
			break;
		case R.id.xiangqing_lijigoumai:
			pay();
			break;
		default:
			break;
		}
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus) {
			searchLayoutTop = rlayout.getBottom();
		}
	}

	@Override
	public void onScroll(int scrollY) {
		if (scrollY >= searchLayoutTop) {
			if (radioG.getParent() != search01) {
				search02.removeView(radioG);
				search01.addView(radioG);
			}
		} else {
			if (radioG.getParent() != search02) {
				search01.removeView(radioG);
				search02.addView(radioG);
			}
		}
	}

	private void showShare() {
		ShareSDK.initSDK(this);
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();

		// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		oks.setTitle("御泥坊APP");
		// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
		oks.setTitleUrl("http://sharesdk.cn");
		// text是分享文本，所有平台都需要这个字段
		oks.setText("我是分享文本");
		// 分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
		oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
		// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
		// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
		// url仅在微信（包括好友和朋友圈）中使用
		oks.setUrl("http://sharesdk.cn");
		// comment是我对这条分享的评论，仅在人人网和QQ空间使用
		oks.setComment("我是测试评论文本");
		// site是分享此内容的网站名称，仅在QQ空间使用
		oks.setSite(getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用
		oks.setSiteUrl("http://sharesdk.cn");

		// 启动分享GUI
		oks.show(this);
	}
	public void pay() {
		if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE) || TextUtils.isEmpty(SELLER)) {
			new AlertDialog.Builder(XiangQingActivity.this).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {
							//
							finish();
						}
					}).show();
			return;
		}
		String orderInfo = getOrderInfo("测试的商品", "该测试商品的详细描述", "0.01");

		/**
		 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
		 */
		String sign = sign(orderInfo);
		try {
			/**
			 * 仅需对sign 做URL编码
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		/**
		 * 完整的符合支付宝参数规范的订单信息
		 */
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(XiangQingActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);
				String version = alipay.getVersion();
				Log.d("TAG", "version: " + version);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(XiangQingActivity.this);
		String version = payTask.getVersion();
		Toast.makeText(XiangQingActivity.this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 原生的H5（手机网页版支付切natvie支付） 【对应页面网页支付按钮】
	 * 
	 * @param v
	 */
	public void h5Pay(View v) {
		Intent intent = new Intent(XiangQingActivity.this, H5PayDemoActivity.class);
		Bundle extras = new Bundle();
		/**
		 * url是测试的网站，在app内部打开页面是基于webview打开的，demo中的webview是H5PayDemoActivity，
		 * demo中拦截url进行支付的逻辑是在H5PayDemoActivity中shouldOverrideUrlLoading方法实现，
		 * 商户可以根据自己的需求来实现
		 */
		String url = "http://m.meituan.com";
		// url可以是一号店或者美团等第三方的购物wap站点，在该网站的支付过程中，支付宝sdk完成拦截支付
		extras.putString("url", url);
		intent.putExtras(extras);
		startActivity(intent);

	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	private String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm" + "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	private String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
